import { ethers } from "ethers";

export const toStringMatch = (data: string, decimal = 2) => {
    if (data) {
        if (decimal == 2) {
            return Number(data.toString().match(/^\d+(?:\.\d{0,2})?/));
        } if (decimal == 3) {
            return Number(data.toString().match(/^\d+(?:\.\d{0,3})?/));
        } else if (decimal == 4) {
            return Number(data.toString().match(/^\d+(?:\.\d{0,4})?/));
        } else if (decimal == 6) {
            return Number(data.toString().match(/^\d+(?:\.\d{0,6})?/));
        } else {
            return Number(data.toString().match(/^\d+(?:\.\d{0,0})?/));
        }

    } else {
        return 0;
    }
}


export const fromWei = (data: string | number, from = "ether", decimal = 2) => {
    if (data) {
        return Number(
            toStringMatch(
                ethers.utils.formatUnits(data.toString(), from).toString(),
                decimal
            )
        );
    } else {
        return 0;
    }
}

export const toWei = (data: string | number, from = "ether") => {
    if (data) {
        return ethers.utils.parseUnits(data.toString(), from).toString()
    } else {
        return 0;
    }
}

export const formatAddress = (address: string, dynamic = 5) => {
    if (address) {
        var subStr1 = address.substr(0, dynamic);
        var subStr2 = address.substr(
            address.length - dynamic,
            dynamic
        );
        var subStr = subStr1 + "..." + subStr2;
        return subStr;
    } else {
        return "";
    }
}

export const formatAddress2 = (address: string, dynamic = 5) => {
    if (address) {
        var subStr1 = address.substr(0, dynamic);
        var subStr2 = address.substr(
            address.length - dynamic,
            dynamic
        );
        var subStr = subStr1 + "..." + subStr2;
        return subStr;
    } else {
        return "";
    }
}

export const formatCurrency = (list: any[], id: number) => {
    const items = list.find(item => item.Id == id)
    var symbols = ""
    switch (items.Id) {
        case 4:
            symbols = "￥"
            break;

        case 20:
            symbols = "$"
            break;

        default:
            symbols = items.Symbol
            break;
    }
    return { ...items, symbols }
}